package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
////        解决缓存穿透问题 通过设置空值
//        Shop shop = queryWithPassThrough(id);
//        解决缓存 击穿问题利用互斥锁
//        Shop shop = queryWithMutex(id);
        Shop shop = queryWithLogicalExpire(id);
        if (shop == null) {
//            如果shop为null的情况下 返回fail
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    private Shop queryWithPassThrough(Long id) {
        //        查Redis缓存
//        查到结果后直接返回 如果查不到 就从数据库中查 如果查到 把结果添加到redis并返回商铺信息  如果在数据库中都查不到返回查询失败
        String shopJSON = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
//        如果不为空那么直接返回
        if (StrUtil.isNotBlank(shopJSON)) {
//            如果能查到直接返回
            return JSONUtil.toBean(shopJSON, Shop.class, false);
        }
//        如果为空那么返回错误信息
        if (shopJSON != null) {
            return null;
        }

//        查询数据库
        Shop shop = getById(id);
//        如果查询不到 那么给redis一个空值
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
//        如果存在 写入redis
        shopJSON = JSONUtil.toJsonStr(shop);
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, shopJSON, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    private Shop queryWithMutex(Long id) {
        //        查Redis缓存
//        查到结果后直接返回 如果查不到 就从数据库中查 如果查到 把结果添加到redis并返回商铺信息  如果在数据库中都查不到返回查询失败
        String shopJSON = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
//        如果不为空那么直接返回
        if (StrUtil.isNotBlank(shopJSON)) {
//            如果能查到直接返回
            return JSONUtil.toBean(shopJSON, Shop.class, false);
        }

//        如果为空那么返回错误信息
        if (shopJSON != null) {
            return null;
        }
//        未命中  尝试获取互斥锁
        String key = null;
        Shop shop = null;
        try {
            key = RedisConstants.LOCK_SHOP_KEY + id;
            boolean isLock = tryLock(key);
//        如果没有获取到锁那么线程等待防止不停的重复获取  等待完成后重新尝试获取锁
            if (!isLock) {
                Thread.sleep(50);
                return queryWithMutex(id);
            }
//        获取到了互斥锁
//            查询数据库
            shop = getById(id);
//            模拟查询数据库出现的延迟
            Thread.sleep(200);
//        如果查不到 给Redis返回一个空值
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
//        如果存在 写入redis
            shopJSON = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, shopJSON, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        释放锁
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {

            unLock(key);
        }
        return shop;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    private Shop queryWithLogicalExpire(Long id) {
        //        查Redis缓存
//        查到结果后直接返回 如果查不到 就从数据库中查 如果查到 把结果添加到redis并返回商铺信息  如果在数据库中都查不到返回查询失败
        String shopJSON = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
//        如果为空那么表示未命中直接返回null
        if (StrUtil.isBlank(shopJSON)) {
//            如果能查到直接返回
            return null;
        }

//        Redis命中
//        将数据反序列化为java对象
        RedisData redisData = JSONUtil.toBean(shopJSON, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class, false);

        LocalDateTime expireTime = redisData.getExpireTime();
//        判断是否过期
        if (!LocalDateTime.now().isAfter(expireTime)) {
//        未过期直接返回店铺信息
            return shop;
        }
//          过期的话会尝试获取互斥锁
        String key = RedisConstants.LOCK_SHOP_KEY + id;
//        获取到锁 会新建一个新的线程  没有获取到会直接返回旧数据
//        注意 这里必须再次校验缓存是否过期
        boolean isLock = tryLock(key);
        if (isLock) {
            shopJSON = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
            redisData = JSONUtil.toBean(shopJSON, RedisData.class);
            expireTime = redisData.getExpireTime();
            //判断是否过期
            if (!LocalDateTime.now().isAfter(expireTime)) {
//              未过期直接返回店铺信息
                return shop;
            }
//            过期的话重新创建一个线程  更新缓存Redis
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    this.saveShop2Redis(id, 20L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
//                    释放锁
                    unLock(key);
                }
            });
        }
        return shop;
    }

    // 封装一个往Redis中存数据的方法 包括过期时间
    private void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
//        从数据库中查询到了数据
        Shop shop = getById(id);
//        模拟数据库查询的延迟
        Thread.sleep(200);
//        设置过期时间和店铺数据
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
//        设置完毕后存入redis
        String jsonStr = JSONUtil.toJsonStr(redisData);
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, jsonStr);
    }

    //    封装一个方法模拟Redis互斥锁  setnx---获取锁
    private Boolean tryLock(String key) {
        Boolean isGetLock = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(isGetLock);
    }

    //    释放锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("该店铺的ID不能为空");
        }
//        1 .更新数据库
        updateById(shop);
//        2. 删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);

        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
//         判断x和y是否有效
        if (x==null||y==null){
            Page<Shop> shopPage = query().eq("type_id", typeId).page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(shopPage.getRecords());
        }
        int  from= (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = stringRedisTemplate.opsForGeo().search(
                RedisConstants.SHOP_GEO_KEY + typeId, GeoReference.fromCoordinate(new Point(x, y)),
                new Distance(5000), RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        assert geoResults != null;
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = geoResults.getContent();

        List<Long> ids = new ArrayList<>(content.size());
        Map<String,Distance> distanceMap = new HashMap<>(content.size());
        if (content.size()<=from){
            return Result.ok(Collections.emptyList());
        }
        content.stream().skip(from).forEach(result->{
            String id = result.getContent().getName();
            ids.add(Long.valueOf(id));
            Distance distance = result.getDistance();
            distanceMap.put(id, distance);
        });
        String join = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + join + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }
}
